package com.imist.nettybasic4.server.handler;

import com.imist.nettybasic4.protocol.request.ListGroupMembersRequestPacket;
import com.imist.nettybasic4.protocol.response.ListGroupMembersResponsePacket;
import com.imist.nettybasic4.session.Session;
import com.imist.nettybasic4.utils.SessionUtils;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;

import java.util.ArrayList;
import java.util.List;
@ChannelHandler.Sharable
public class ListGroupMemberRequestHandler extends SimpleChannelInboundHandler<ListGroupMembersRequestPacket> {
    public static final ListGroupMemberRequestHandler INSTANCE = new ListGroupMemberRequestHandler();

    protected ListGroupMemberRequestHandler() {
    }
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, ListGroupMembersRequestPacket listGroupMembersRequestPacket) throws Exception {
        // 1. 获取群的ChannelGroup
        String groupId  = listGroupMembersRequestPacket.getGroupId( );
        ChannelGroup channels = SessionUtils.getChannelGroup(groupId);
        //2.遍历群成员的channel,对应的session，构建群成员的信息
        List<Session> sessionList = new ArrayList<>();
        for (Channel channel : channels) {
            Session session = SessionUtils.getSession(channel);
            sessionList.add(session);
        }
        //3.构建获取成员列表响应写回到客户端
        ListGroupMembersResponsePacket responsePacket = new ListGroupMembersResponsePacket();
        responsePacket.setGroupId(groupId);
        responsePacket.setSessionList(sessionList);
        channelHandlerContext.writeAndFlush(responsePacket);
    }
}
